import ReconnectingWebSocket from "reconnecting-websocket";
import networkConfiguration from "@/network/configuration";
import usePeerStore from "@/store/peer";
import useFriendStore from "@/store/friend";
import msgRecordStore from "@/store/msgRecord";
import {showToast} from "vant";
import {getToken} from "@/util/auth";
let connection = null;
export default {
    install(app) {
        console.log("invoked initialize websocket plugin");
        app.config.globalProperties.$initializePeer?.then(() => {
            let peerStore = usePeerStore();
            let friendStore = useFriendStore();
            let recordStore = msgRecordStore();

            let {host, port, path} = {...networkConfiguration.server.webSocketServer};
            let peerId = peerStore.localPeer.id;
            let paramStr = "?connectType=USER&Authorization=" + "Bearer " + getToken() + "&peerId=" + peerId;

            connection = new ReconnectingWebSocket(`ws://${host}:${port}${path}` + paramStr);

            connection.onmessage = event => {
                let message = JSON.parse(event.data);
                if (friendStore.onlineList){
                    friendStore.onlineList.forEach(item =>{
                        if (item.userName == message.fromUser || item.friendUserName == message.fromUser){
                            if(message.eventType == 0){
                                item.onlineStatus = 1
                                item.onlineStatusText = '在线'
                            }
                            if(message.eventType == 1){
                                item.onlineStatus = 0
                                item.onlineStatusText = '不在线'
                            }
                        }
                    })
                }
                if(message.eventType == 2){
                    // 聊天室消息 先查询是否正在和该好友聊天
                    if (recordStore.friendUserName == message.fromUser){
                        // 正在聊天 插入信息
                        recordStore.msgList.push({
                            fromUser: message.fromUser,
                            msg: message.msg,
                            msgId: message.msgId,
                            createTime: message.createTime,
                            sendTime: message.sendTime,
                            type: 'received',
                        })
                    }
                }
                // friendStore.onlineList = message;
                console.log("webSocketConnection.onmessage:", message);
            };


            connection.onclose = event => {
                console.log("webSocketConnection.onclose:", event);
                showToast("network connection closed");
            };

            connection.onerror = event => {
                console.log("webSocketConnection.onerror:", event);
                // 重新获取下token
                paramStr = "?connectType=USER&Authorization=" + "Bearer " + getToken() + "&peerId=" + peerId;
                connection._url = `ws://${host}:${port}${path}` + paramStr
                showToast("network connection error");
            };

            connection.onopen = event => {
                console.log("webSocketConnection.onopen:", event);
            };
        });
    },
    send(data){
        connection.send(data);
    }
};
